import axios from 'axios'
import {Message,Notification} from 'element-ui'
import router from '../router'
import {Loading} from 'element-ui';
import {baseURL} from "../util";

let instance = axios.create({
    withCredentials: true
});
instance.timeout = 8000;
instance.defaults.baseURL = baseURL;
instance.defaults.headers = {"Content-Type": "application/x-www-form-urlencoded"};
const options = {
    text: 'Processing...'
};
let loadingInstance;
instance.interceptors.request.use((config) => {
    loadingInstance = Loading.service(options);
    return config;
}, err => {
    return Promise.reject(err);
});

instance.interceptors.response.use((response) => {
    loadingInstance.close();
    return response;
}, (error) => {
    if(error.response){
        switch (error.response.status){
            case 403: //应该是401 //TODO
                router.replace('/');
                loadingInstance.close();
                break;
            case 500:
                Notification.error('Service is not available right now');
                break;
            case 404:
                Notification.error('No Service');
                break;
            case 503:
                Notification.error('Server is not available right now');
                break;
            default:
                console.log(error.response)
        }
    } else {
        Notification.error('网络环境异常');
    }

    loadingInstance.close();
    return Promise.reject(error);

});

export default instance;